package twitter.client.adapter;

import java.util.List;

import twitter.client.R;
import twitter.client.task.ImageDownloadTask;
import twitter.client.util.ImageChace;
import twitter.client.util.Utils;
import twitter4j.Status;
import twitter4j.User;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class TimelineListAdapter extends ArrayAdapter<Status> {
	private LayoutInflater inflater;
	private Context context;
	private List<Status> listData;
	private int resource;
	
	public TimelineListAdapter(Context context, int resource, List<Status> listData){
		super(context, resource, listData);
		
		this.context = context;
		this.listData = listData;
		this.resource = resource;
		this.inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		if (convertView == null) {
			convertView = this.inflater.inflate(this.resource, null);
		}
		
		Status status = this.listData.get(position);
		User user = status.getUser();
		
		ImageView profImage = (ImageView) convertView.findViewById(R.id.tlProfImage);
		TextView twitterIdText = (TextView) convertView.findViewById(R.id.tlTwitterId);
		TextView tweetTextText = (TextView) convertView.findViewById(R.id.tlTweetText);
		TextView tweetInfoText = (TextView) convertView.findViewById(R.id.tlTweetInfo);
		
		String imageUrl = user.getProfileImageURL().toString();
		Bitmap image = ImageChace.getImage(imageUrl);
		profImage.setTag(imageUrl);
		if(image != null){
			profImage.setImageBitmap(image);
		}else{
			profImage.setImageResource(R.drawable.default_prof_image);
			ImageDownloadTask task = new ImageDownloadTask(profImage, this.context);
			task.execute(imageUrl);
		}
		
		twitterIdText.setText(user.getScreenName()+"("+user.getName()+")");
		tweetTextText.setText(status.getText());
		tweetInfoText.setText(Utils.getTweetInfo(status.getCreatedAt(), status.getSource()));
		
		return convertView;
	}
	
	public List<Status> getData(){
		return this.listData;
	}
}
